/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryCommentPraiseNumAction;

import logic.bean.BookInfo;
import logic.bean.NumberInfo;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;


/**
 * @Project：
 * @Title：ImageTextActivity
 * @Description：图文详情页
 * @Author：zhangnannan
 * @Date：2015年1月
 */
public class ImageTextActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener
{
	private TextView              tvTitle;
	private ImageView                btnBack;
	private WebView               webView;
	private Context               mContext;
	private FrameLayout           mFLayout;
	
	private String                mTitle;
	private String                mUrl;
	private String                targetType;
	private String                targetValue;
	/***** 分享 ******/
	private RelativeLayout        rlayShare;
	/***** 评论 ******/
	private RelativeLayout        rlayComment;
	private TextView              tvComment;
	/***** 点赞 ******/
	private RelativeLayout        rlayGood;
	private TextView              tvGood;
	/***** 收藏 ******/
	private RelativeLayout        rlayCollect;
	
	private RelativeLayout        llayTopTitle;
	private LinearLayout          llayBottomTools;
	private LoadingView           loadingView;
	
	private HarlanWebChromeClient chromeClient = null;
	private CustomViewCallback    myCallBack   = null;
	private View                  myView       = null; //视频全屏时的view
	                                                   
	private Handler               myHandler    = new Handler()
	                                           {
		                                           
		                                           @Override
		                                           public void handleMessage(Message msg) {
			                                           Bundle bundle = msg.getData();
			                                           switch (msg.what) {
														   case 1:
															   String bookId = bundle.getString("bookId");
															   String name = bundle.getString("bookName");
															   String type = bundle.getString("bookType");
															   gotoBookDetail(bookId, name, type);
															   break;
														   
														   default:
															   break;
													   }
												   }
												   
	                                           };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.imagetext);
		final Bundle bundle = getIntent().getExtras();
		if (bundle.containsKey(DefaultConsts.title_s) && bundle.containsKey(DefaultConsts.req_url_s) && bundle.containsKey(DefaultConsts.COMMENT_TARGET_TYPE) && bundle.containsKey(DefaultConsts.COMMENT_TARGET_VALUE))
		{
			mTitle = bundle.getString(DefaultConsts.title_s);
			mUrl = bundle.getString(DefaultConsts.req_url_s);
			targetType = bundle.getString(DefaultConsts.COMMENT_TARGET_TYPE);
			targetValue = bundle.getString(DefaultConsts.COMMENT_TARGET_VALUE);
		}
		else
		{
			finish();
			return;
		}
		
		initView();
		initLoadingView();
		setListener();
		setWebView();
		if (savedInstanceState != null)
		{
			webView.restoreState(savedInstanceState);
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		webView.saveState(outState);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (NetworkUtil.isNetAvailable(mContext))
		{
			new QryCommentPraiseNumAction(mContext, targetType, targetValue, new PraiseNumListener()).start();
		}
	}
	
	private class PraiseNumListener
	        extends
	        BaseAction
	{
		@Override
		public void OK(Object obj) {
			final NumberInfo info = (NumberInfo) obj;
			if (null != info)
			{
				myHandler.post(new Runnable()
				{
					@Override
					public void run() {
						tvComment.setText(info.commentNum == 0 ? "" : String.valueOf(info.commentNum));
						tvGood.setText(info.praiseNum == 0 ? "" : String.valueOf(info.praiseNum));
					}
				});
			}
		}
	}
	
	void initView() {
		
		btnBack = (ImageView) findViewById(R.id.imagetext_top_title_back_btn);
		btnBack.setVisibility(View.VISIBLE);
		mFLayout = (FrameLayout) findViewById(R.id.imagetext_flay);
		webView = (WebView) findViewById(R.id.imagetext_webview);
		llayTopTitle = (RelativeLayout) findViewById(R.id.imagetext_top_title_lay);
		llayBottomTools = (LinearLayout) findViewById(R.id.imagetext_bottom_tools_lay);
		llayTopTitle.setVisibility(View.VISIBLE);
		llayBottomTools.setVisibility(View.VISIBLE);
		
		rlayShare = (RelativeLayout) findViewById(R.id.imagetext_bottom_share);
		rlayComment = (RelativeLayout) findViewById(R.id.imagetext_bottom_comment);
		rlayGood = (RelativeLayout) findViewById(R.id.imagetext_bottom_good);
		rlayCollect = (RelativeLayout) findViewById(R.id.imagetext_bottom_collect);
		loadingView = (LoadingView) findViewById(R.id.imagetext_loading_view);
		tvComment = (TextView) findViewById(R.id.imagetext_bottom_comment_textview);
		if (targetType.equals("5")) llayBottomTools.setVisibility(View.GONE);
		tvGood = (TextView) findViewById(R.id.imagetext_bottom_good_textview);
	}
	
	private void initLoadingView() {
		loadingView.setLoadingAnim(R.drawable.home_progress);
		//		loadingView.setLoadingAnim(R.anim.column_switch_anim);
		loadingView.changeLoadingStatus(0);
		
		loadingView.setVisibility(View.VISIBLE);
		mFLayout.setVisibility(View.GONE);
	}
	
	void setListener() {
		btnBack.setOnClickListener(this);
		rlayShare.setOnClickListener(this);
		rlayComment.setOnClickListener(this);
		rlayGood.setOnClickListener(this);
		rlayCollect.setOnClickListener(this);
		
		webView.setOnTouchListener(new OnTouchListener()
		{
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				//				  pY = (int) event.getY();
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						//						tempY = pY;
						pY = (int) event.getY();
						
						break;
					case MotionEvent.ACTION_MOVE:
						tempY = (int) event.getY();
						dY = tempY - pY;
						//						int dY = pY - tempY;
						//		                tempY = pY;
						if (dY > 0)
						{
							//向下滑
							llayTopTitle.setVisibility(View.VISIBLE);
							if (!targetType.equals("5")) llayBottomTools.setVisibility(View.VISIBLE);
							
						}
						else if (dY < 0)
						{
							//向上滑 
							llayTopTitle.setVisibility(View.GONE);
							llayBottomTools.setVisibility(View.GONE);
							
						}
						break;
					case MotionEvent.ACTION_UP:
						clear();
						break;
					default:
						break;
				}
				
				return false;
			}
			
		});
		
	}
	
	private int tempY = 0;
	private int pY    = 0;
	private int dY    = 0;
	
	private void clear() {
		tempY = 0;
		pY = 0;
		dY = 0;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.imagetext_top_title_back_btn:
				goback();
				break;
			case R.id.imagetext_bottom_share:
				clickShare();
				break;
			case R.id.imagetext_bottom_comment:
				clickComment();
				break;
			case R.id.imagetext_bottom_good:
				clickGood();
				break;
			case R.id.imagetext_bottom_collect:
				clickCollect();
				break;
			default:
				break;
		}
	}
	
	/** 收藏 */
	private void clickCollect() {
		Util.showToast(mContext, "您点击了收藏");
	}
	
	/** 点赞 */
	private void clickGood() {
		Util.showToast(mContext, "您点击了点赞");
	}
	
	/** 评论 */
	private void clickComment() {
		//		Util.showToast(mContext, "您点击了评论");
		Intent intent1 = new Intent();
		intent1.setClass(mContext, CommentListActivity.class);
		intent1.putExtra(DefaultConsts.COMMENT_TARGET_TYPE, targetType);
		intent1.putExtra(DefaultConsts.COMMENT_TARGET_VALUE, targetValue);
		startActivity(intent1);
	}
	
	/** 分享 */
	private void clickShare() {
		Util.showToast(mContext, "您点击了分享");
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack())
		{
			webView.goBack();// 返回前一个页面
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	void goback() {
		if (!targetType.equals("5") && webView.canGoBack())
		{
			webView.goBack();
		}
		else
		{
			onBackPressed();
		}
	}
	
	@Override
	public void onBackPressed() {
		if (myView == null)
		{
			webView.onPause(); //退出播放停止
			super.onBackPressed();
			if (!existMainActivity())
			{
				startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
			}
		}
		else
		{
			chromeClient.onHideCustomView();
		}
		
	}
	
	@SuppressLint ("SetJavaScriptEnabled")
	private void setWebView() {
		/*
		 * webSettings 保存着WebView中的状态信息。
		 * 当WebView第一次被创建时，webSetting中存储的都为默认值。
		 * WebSetting和WebView一一绑定的。
		 * 如果webView被销毁了，那么我们再次调用webSetting中的方法时，会抛出异常。
		 */
		WebSettings webSettings = webView.getSettings();
		//允许在webview中执行JavaScript代码
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setDomStorageEnabled(true);
		//设置web页面不读取缓存
		//		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		
		//设置webview是否支持缩放
		webSettings.setSupportZoom(false);
		
		webSettings.setPluginState(PluginState.ON);
		webSettings.setLoadWithOverviewMode(true);
		
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		
		webView.setHorizontalScrollBarEnabled(false);
		webView.setVerticalScrollBarEnabled(true);
		webSettings.setUseWideViewPort(true); //适应屏幕
		
		chromeClient = new HarlanWebChromeClient();
		webView.setWebChromeClient(chromeClient);
		webView.setWebViewClient(new HarlanWebViewClient());
		
		if (Util.isEmpty(mUrl))
		{
			loadingView.setVisibility(View.GONE);
			mFLayout.setVisibility(View.VISIBLE);
		}
		else
		{
			webView.loadUrl(Util.addUrlTimestamp(mUrl));
		}
		
		/*
		 * 为js提供一个方法，注意该方法一般不写在UI线程中
		 * addJavascriptInterface(Object obj, String interfaceName)
		 * obj代表一个java对象，这里我们一般会实现一个自己的类，类里面提供我们要提供给javascript访问的方法
		 * interfaceName则是访问我们在obj中声明的方法时候所用到的js对象，调用方法为window.interfaceName.方法名(
		 * )
		 */
		webView.addJavascriptInterface(new SubMaintenanceJavaScriptInterface(), "qyreader");
	}
	
	final class SubMaintenanceJavaScriptInterface
	{
		
		/** 在屏幕下端提示用户 */
		public void setBookInfo(String bookId, String bookName, String bookType) {
			LogUtil.d("--", "bookId：" + bookId + " | bookName:" + bookName + " |bookType:" + bookType);
			sendToastMessage(bookId, bookName, bookType);
		}
		
		/** 提供给B端打印日志 */
		public void fireLog(String log) {
			LogUtil.d("dddd", log);
		}
		
		/**
		 * 假如有历史记录 回退历史记录 否则退出容器
		 */
		public void goBack() {
			myHandler.post(new Runnable()
			{
				@Override
				public void run() {
					onBackPressed();
				}
			});
		}
	}
	
	private void sendToastMessage(String bookId, String bookName, String bookType) {
		
		Message msg = Message.obtain();
		msg.what = 1;
		Bundle bundle = new Bundle();
		bundle.putString("bookId", bookId);
		bundle.putString("bookName", bookName);
		bundle.putString("bookType", bookType);
		msg.setData(bundle);
		myHandler.sendMessage(msg);
	}
	
	private void gotoBookDetail(String bookId, String name, String bookType) {
		BookInfo info = new BookInfo();
		info.setBookId(Long.parseLong(bookId));
		info.setName(name);
		info.setContent_type(bookType);
		//#ifdef SHOW_OLDBOOKDETAIL
		//$ Intent intent = new Intent(this, BookDetailActivity.class);
		//#else
		Intent intent = new Intent(this, NewBookDetailActivity.class);
		//#endif
		intent.putExtra("BookInfo", info);
		startActivity(intent);
		
	}
	
	/***
	 * webChromeClient主要是将javascript中相应的方法翻译成android本地方法
	 * 例如：我们重写了onJsAlert方法，那么当页面中需要弹出alert窗口时，便
	 * 会执行我们的代码，按照我们的Toast的形式提示用户。
	 */
	class HarlanWebChromeClient
	        extends
	        WebChromeClient
	{
		
		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			if (myView != null)
			{
				callback.onCustomViewHidden();
				return;
			}
			mFLayout.removeView(webView);
			mFLayout.addView(view);
			myView = view;
			myCallBack = callback;
		}
		
		@Override
		public void onHideCustomView() {
			if (myView == null) { return; }
			mFLayout.removeView(webView);
			myView = null;
			mFLayout.addView(webView);
			myView = null;
			
			myCallBack.onCustomViewHidden();
		}
		
		@Override
		public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
			// TODO Auto-generated method stub
			Log.d("ZR", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
			return super.onConsoleMessage(consoleMessage);
		}
		
		/*
		 * 此处覆盖的是javascript中的alert方法。
		 * 当网页需要弹出alert窗口时，会执行onJsAlert中的方法
		 * 网页自身的alert方法不会被调用。
		 */
		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			Util.showToast(mContext, message);
			/*
			 * 此处代码非常重要，若没有，android就不能与js继续进行交互了，
			 * 且第一次交互后，webview不再展示出来。
			 * result：A JsResult to confirm that the user hit enter.
			 * 我的理解是，confirm代表着此次交互执行完毕。只有执行完毕了，才可以进行下一次交互。
			 */
			result.confirm();
			return true;
		}
		
		/*
		 * 此处覆盖的是javascript中的confirm方法。
		 * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
		 * 网页自身的confirm方法不会被调用。
		 */
		@Override
		public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
			return true;
		}
		
		/*
		 * 此处覆盖的是javascript中的confirm方法。
		 * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
		 * 网页自身的confirm方法不会被调用。
		 */
		@Override
		public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
			return true;
		}
		
		/*
		 * 如果页面被强制关闭,弹窗提示：是否确定离开？
		 * 点击确定 保存数据离开，点击取消，停留在当前页面
		 */
		@Override
		public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
			return true;
		}
	}
	
	class HarlanWebViewClient
	        extends
	        WebViewClient
	{
		
		@Override
		public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
			WebResourceResponse response = null;
			response = super.shouldInterceptRequest(view, url);
			return response;
		}
		
		/*
		 * 点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
		 * 因此，要在shouldOverrideUrlLoading方法中
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			//使用当前的WebView加载页面
			if (url.contains("tel:"))
			{
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_DIAL);
				intent.setData(Uri.parse(url));
				startActivity(intent);
				return true;
			}
			view.loadUrl(url);
			return true;
		}
		
		/*
		 * 网页加载完毕(仅指主页，不包括图片)
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}
		
		/*
		 * 网页加载完毕(仅指主页，不包括图片)
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			loadingView.setVisibility(View.GONE);
			mFLayout.setVisibility(View.VISIBLE);
		}
		
		/*
		 * 加载页面资源
		 */
		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}
		
		/*
		 * 错误提示
		 */
		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			loadingView.setVisibility(View.GONE);
			mFLayout.setVisibility(View.VISIBLE);
		}
	};
}
